package com.ruoyi.mqtt.config;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.json.JSONUtil;
import com.ruoyi.mqtt.consts.MqSensorsEnums;
import com.ruoyi.mqtt.dto.MqMessage;
import com.ruoyi.mqtt.entity.MessageEntity;
import com.ruoyi.mqtt.mapper.MqMessageMapper;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttMessageListener;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class MessageCallbackListener implements IMqttMessageListener{
//    private final RedisTemplate<String, String> redisTemplate;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    MqMessageMapper mqMessageMapper;
    @Autowired
    MqttResponseHolder responseHolder;


//    @Autowired
//    public MessageCallbackListener(RedisTemplate<String, String> redisTemplate) {
//        this.redisTemplate = redisTemplate;
//    }
    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {

        String messageBody = new String(message.getPayload(), StandardCharsets.UTF_8);
        MqMessage mqMessage = JSONUtil.toBean(messageBody, MqMessage.class);
        // 假设温度数据格式为 "tempRead:25.0"
        if (MqSensorsEnums.SENSOR_TEMPERATURE.getCode().equals(mqMessage.getType())
        && MqSensorsEnums.SENSOR_REQUEST_TYPE_RECEIVE.getCode().equals(mqMessage.getRequestType())) {
            String value = mqMessage.getValue();
            redisTemplate.opsForValue().set("latestTemperature",value,60, TimeUnit.SECONDS);
            String requestId = mqMessage.getRequestId();
            responseHolder.completeRequest(requestId, mqMessage.getValue());
            MessageEntity entity = new MessageEntity();
            BeanUtil.copyProperties(mqMessage,entity);
            entity.setCreateTime(DateTime.now());
            entity.setUpdateTime(DateTime.now());
            try{
                mqMessageMapper.insert(entity);
            } catch (Exception e) {
                log.error("插入数据库失败：{}", e.getMessage());
            }

            log.info("收到温度数据：" + value);
        }
        System.out.println("收到消息："+topic+", 消息内容是："+ messageBody);
    }
}
